package com.shop.service.impl;

import com.shop.entity.CartItem;
import com.shop.entity.Product;
import com.shop.entity.User;
import com.shop.exception.ResourceNotFoundException;
import com.shop.repository.CartItemRepository;
import com.shop.repository.ProductRepository;
import com.shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    
    @Autowired
    private CartItemRepository cartItemRepository;
    
    @Autowired
    private ProductRepository productRepository;
    
    @Override
    public CartItem addToCart(Long userId, Long productId, Integer quantity) {
        CartItem existingItem = cartItemRepository.findByUserIdAndProductId(userId, productId);
        
        if (existingItem != null) {
            existingItem.setQuantity(existingItem.getQuantity() + quantity);
            return cartItemRepository.save(existingItem);
        }
        
        Product product = productRepository.findById(productId)
            .orElseThrow(() -> new ResourceNotFoundException("Product not found"));
            
        CartItem cartItem = new CartItem();
        cartItem.setUser(new User(userId));
        cartItem.setProduct(product);
        cartItem.setQuantity(quantity);
        
        return cartItemRepository.save(cartItem);
    }
}